<template>
  <div>
    <div class="actual-right" style="padding-top: 30px;">
      <div class="one">
        <div class="title">
          <span>{{ pfqd1.title }}</span>
        </div>
        <div class="list">
          <div class="item" v-for="(item, index) in pfqd1.list" :key="index">
            <div :class="item.istop ? 'top-triangle' : 'btm-triangle'"></div>
            <div class="num">{{ proFormat2(item.num) }}<span>kg</span></div>
            <div class="text nox">{{ item.name }}</div>
          </div>
        </div>
      </div>
      <div class="one">
        <div class="title">
          <span>{{ pfqd2.title }}</span>
        </div>
        <div class="list">
          <div class="item" v-for="(item, index) in pfqd2.list" :key="index">
            <div :class="item.istop ? 'top-triangle' : 'btm-triangle'"></div>
            <div class="num">{{ proFormat2(item.num) }}<span>kg</span></div>
            <div class="text nox">{{ item.name }}</div>
          </div>
        </div>
      </div>
      <div class="two">
        <LinePage :LinePageDate="LinePageDate" titleText="近七天日排放量(吨)" titleColor="#e9eef3" :titleSize="22"
          :textUnit="textUnit" :Name="Name"></LinePage>
      </div>
      <div class="three">
        <div class="title-container">
          <div class="title">排放热点区</div>
          <div class="pollutant-selector">
            <el-radio-group
              v-model="selectedPollutant"
              size="mini"
              class="compact-radio-group"
            >
              <el-radio
                v-for="option in pollutantOptions"
                :key="option.value"
                :label="option.value"
                class="compact-radio"
                @change="updateRanks"
              >
                {{ option.label }}
              </el-radio>
            </el-radio-group>
          </div>
        </div>

        <div class="pro-list">
          <div class="pro-item" v-for="(item, key) in ranks" :key="key">
            <div class="pro-label">
              <div class="ranking">{{ key + 1 }}</div>
              <span>{{ TJRegions[item.name] }}</span>
            </div>
            <div class="pro">
              <el-progress :percentage="percentage(ranks[0].value, item.value)" :type="pro1.type"
                :stroke-width="pro1.strokeWidth" :color="pro1.color" :show-text="false"></el-progress>
            </div>
            <div class="num">
              <span>{{ item.value }}</span>
              <span>吨</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getCarDischargeLast5m,
  getCarDischargeLastHour,
  getCarDischargeLastWeek,
  getCarDischargeByToday,
  getOneRegionSumTotal,
  getOneRegionSumTotalByTime,
  getAllRegionSumTotal,
  getRegionDict,
} from "@/api/largescreen";
import { mapState } from "vuex";

import LinePage from "@/components/Myecharts/LinePage";
import * as dayjs from "dayjs";

export default {
  name: "discharge",
  components: {
    LinePage,
  },
  data() {
    return {
      RegionDict1: [],
      RegionDict2: [],
      /*右侧两块排放强度参数*/
      pfqd1: {
        title: "",
        list: [
          {
            name: "NOX",
            istop: true,
            num: "",
          },
          {
            name: "PM2.5",
            istop: false,
            num: "",
          },
          {
            name: "VOCs",
            istop: false,
            num: "",
          },
          {
            name: "SO₂",
            istop: false,
            num: "",
          },
        ],
      },
      pfqd2: {
        title: "",
        list: [
          {
            name: "NOX",
            istop: false,
            num: "",
          },
          {
            name: "PM2.5",
            istop: false,
            num: "",
          },
          {
            name: "VOCs",
            istop: false,
            num: "",
          },
          {
            name: "SO₂",
            istop: true,
            num: "",
          },
        ],
      },
      /*右侧侧进度条参数*/
      pro1: {
        type: "line",
        strokeWidth: 16,
        color: ["#1af5c4", "#05d3ff"],
      },
      regionsEmission: {},
      TJRegions: {},
      ranks: [],
      /*右侧排放曲线图*/
      LinePageDate: {
        lpweek: [],
        nox: [],
        pm25: [],
        vocs: [],
        so2: [],
      },
      textUnit: ["(吨)"],
      Name: ["NOX", "PM2.5", "VOCs", "SO₂"],
      selectedPollutant: 'nox', // Default selected pollutant
      pollutantOptions: [
        { value: 'nox', label: 'NOX' },
        { value: 'pm25', label: 'PM2.5' },
        { value: 'vocs', label: 'VOCs' },
        { value: 'so2', label: 'SO₂' },
        { value: 'co', label: 'CO' }
      ],
    };
  },
  computed: {
    // ...mapState({
    //   adcode: (state) => state.map.adcode,
    //   hotsportCode: (state) => state.map.hotsportCode,
    // })
    adcode() {
      return 120000
    },
    hotsportCode() {

    },
  },
  mounted() {
    this.isPath();
    this.DischargeLast5m(1);
    this.DischargeLastWeek(1)
    this.DischargeLastHour(1);
    //         this.DischargeLastWeek(newValue);
  },
  methods: {
    /*判断不同的页面请求不同的接口*/

    isPath() {

      if (this.$route.name !== "hotspot") {
        this.pfqd1.title = "实时排放强度（10分钟）";
        this.pfqd2.title = "上一小时排放强度";
        this.DischargeByToday();
      } else {

        this.pfqd1.title = "上一小时排放量";
        this.pfqd2.title = "上一日排放量";
        this.GetRegionDict("gyy");
        this.GetRegionDict("gkd");
      }
    },
    /*查询字典*/
    GetRegionDict(type) {
      getRegionDict({
        dictType: "region",
        type: type,
      })
        .then((res) => {
          let data = res.data;
          this.Dataformat(data, type);
        })
        .catch();
    },
    /*格式化数据*/
    Dataformat(data, str) {
      if (str === "gyy") {
        let arry = [];
        for (let key in data) {
          let obj = {};
          obj.value = key;
          obj.label = data[key];
          arry.push(obj);
        }
        this.RegionDict1 = arry;
      } else {
        let arry = [];
        for (let key in data) {
          let obj = {};
          obj.value = key;
          obj.label = data[key];
          arry.push(obj);
        }
        this.RegionDict2 = arry;
      }
    },
    /*计算排放热点区百分比*/
    percentage(a, b) {
      let num = b / a;
      if (num < 1) {
        return num.toFixed(2) * 100;
      } else {
        return num * 100;
      }
    },
    /*保留小数*/
    proFormat2(number) {
      if (number !== "") {
        let num = number.toFixed(3);
        return this.myfun.myformat(num);
      }
    },
    /*周接口数据处理*/
    WeekData(data) {
      let that = this;
      let xarry = [];
      data.forEach((item, index) => {
        let day = that.myfun.getWeek();
        xarry.push({
          ...item,
          day: item.dayTime,
        });
      });
      /*只保留一周*/
      /*xarry.shift()*/
      let xday = []; // 存储星期
      let nox = []; // 存储nox
      let pm25 = []; // 存储pm25
      let vocs = []; // 存储vocs
      let so2 = []; // 存储so2
      xarry.map((v, k) => {
        xday.push(v.day);
        nox.push(v.totalNox.toFixed(4));
        pm25.push(v.totalPm25.toFixed(4));
        vocs.push(v.totalVocs.toFixed(4));
        so2.push(v.totalSo2.toFixed(4));
      });
      that.LinePageDate.lpweek = xday;
      that.LinePageDate.nox = nox;
      that.LinePageDate.pm25 = pm25;
      that.LinePageDate.vocs = vocs;
      that.LinePageDate.so2 = so2;
    },
    /*排放热点区接口*/
    DischargeByToday() {
      getCarDischargeByToday()
        .then((res) => {
          const a = res.data; // 假设 a 是数组
          this.regionsEmission =  res.data;
          // 处理排名数据
          const b = a.map((item, index) => ({
            name: index, // 或 parseFloat(index)，根据实际需求
            value: parseFloat(item.totalNox.toFixed(3)),
          }));

          b.sort((a, b) => b.value - a.value);
          const c = b.splice(0, 7);

          // 处理区域映射
          const tmp = {};
          a.forEach((item, index) => {
            tmp[index] = item.district;
          });

          this.ranks = c;
          this.TJRegions = tmp;
        })
        .catch((error) => {
          console.error('获取数据失败:', error);
        });
    },
     updateRanks() {
      if (!this.regionsEmission || !this.regionsEmission.length) return;

      // Build the property name for the selected pollutant
      const property = `total${this.selectedPollutant.charAt(0).toUpperCase() + this.selectedPollutant.slice(1)}`;

      // Create new rankings based on selected pollutant
      const newRanks = this.regionsEmission.map((region, index) => ({
        name: index,
        value: region[property] ? parseFloat(region[property].toFixed(3)) : 0
      }));

      // Sort and take top 7
      newRanks.sort((a, b) => b.value - a.value);
      this.ranks = newRanks.slice(0, 7);
    },
    /*实时排放强度*/
    DischargeLast5m(id) {
      getCarDischargeLast5m({ cId: id }).then((res) => {
        let data = res.data;
        this.pfqd1.list[0].num = data.totalNox;
        this.pfqd1.list[1].num = data.totalPm25;
        this.pfqd1.list[2].num = data.totalVocs;
        this.pfqd1.list[3].num = data.totalSo2;
      });
    },
    /*上一小时排放强度*/
    DischargeLastHour(id) {
      getCarDischargeLastHour({ cId: id }).then((res) => {
        // console.log(res.data)
        let data = res.data;
        this.pfqd2.list[0].num = data.totalNox;
        this.pfqd2.list[1].num = data.totalPm25;
        this.pfqd2.list[2].num = data.totalVocs;
        this.pfqd2.list[3].num = data.totalSo2;
      });
    },
    /*上一周排放量汇总(吨)*/
    DischargeLastWeek(id) {
      getCarDischargeLastWeek({ cId: id }).then((res) => {
        /*console.log(res.data)*/
        let data = res.data;
        this.WeekData(data);
      });
    },
    /*某区域排放量汇总*/
    GetOneRegionSumTotal(newArry, end, start) {
      if (end && start) {
        getOneRegionSumTotal({
          regionId: newArry[1],
          regionType: newArry[0],
          endTime: end,
          stTime: start,
        })
          .then((res) => {
            let data = res.data;
            this.pfqd1.list[0].num = data.nox;
            this.pfqd1.list[1].num = data.pm25;
            this.pfqd1.list[2].num = data.vocs;
            this.pfqd1.list[3].num = data.so2;
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        getOneRegionSumTotal({ regionId: newArry[1], regionType: newArry[0] })
          .then((res) => {
            let data = res.data;
            this.pfqd2.list[0].num = data.nox;
            this.pfqd2.list[1].num = data.pm25;
            this.pfqd2.list[2].num = data.vocs;
            this.pfqd2.list[3].num = data.so2;
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    /*某区域排放量统计-按时间*/
    GetOneRegionSumTotalByTime(newArry) {
      getOneRegionSumTotalByTime({
        regionId: newArry[1],
        regionType: newArry[0],
      })
        .then((res) => {
          let data = res.data;
          this.WeekData(data);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    /*当日所有区域排放量汇总*/
    GetAllRegionSumTotal(newArry) {
      getAllRegionSumTotal({ regionType: newArry[0] })
        .then((res) => {
          let that = this;
          let data = res.data;
          let List = [];
          for (let key in data) {
            List.push({
              name: key,
              value: parseFloat(data[key].nox.toFixed(3)),
            });
          }
          List.sort(function (a, b) {
            return b.value - a.value;
          });
          let MyNeedList = List.splice(0, 5);
          let RegionDict;
          if (newArry[0] === "gyy") {
            RegionDict = this.RegionDict1;
          } else {
            RegionDict = this.RegionDict2;
          }
          let tmp = {};
          RegionDict.map((v, k) => {
            tmp[v.value] = v.label;
          });
          this.ranks = MyNeedList;
          this.TJRegions = tmp;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  watch: {
    // adcode: {
    //   immediate: true,
    //   deep: true,
    //   handler(newValue, oldValue) {
    //     // console.log(newValue,oldValue)
    //     if (this.$route.name !== "hotspot") {
    //       if (newValue == "120000") {
    //         let id = null;
    //         this.DischargeLast5m(id);
    //         this.DischargeLastHour(id);
    //         this.DischargeLastWeek(id);
    //       } else {
    //         this.DischargeLast5m(newValue);
    //         this.DischargeLastHour(newValue);
    //         this.DischargeLastWeek(newValue);
    //       }
    //     }
    //   },
    // },
    // hotsportCode: {
    //   deep: true,
    //   handler(newValue, oldValue) {
    //     if (this.$route.name === "hotspot") {
    //       if (newValue.length) {
    //         let endStr = dayjs.default().format("YYYY-MM-DD 00:00:00");
    //         let start = dayjs
    //           .default()
    //           .subtract(1, "day")
    //           .format("YYYY-MM-DD 00:00:00");
    //         this.GetOneRegionSumTotal(newValue);
    //         this.GetOneRegionSumTotal(newValue, endStr, start);
    //         this.GetOneRegionSumTotalByTime(newValue);
    //         this.GetAllRegionSumTotal(newValue);
    //       }
    //     }
    //   },
    // },
  },
};
</script>

<style scoped lang="scss">
.actual-right {
  background-color: #172349;
  // background: url('~@/assets/image/main-bg.png') no-repeat center;

  width: 546px;
  height: 100%;
  position: absolute;
  right: 0px;
  top: 90px;
  box-sizing: border-box;
  padding-left: 10px;

  .one {
    width: 100%;
    margin-bottom: 30px;

    .title {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      span {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 22px;
        line-height: 1;
        color: #f0f6fb;
      }
    }

    .list {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .item {
        width: 125px;
        height: 104px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: flex-end;
        background-size: cover;
        position: relative;

        //margin-left: 20px;
        &:nth-child(1) {
          margin-left: 0px;
          background: url("~@/assets/image/nox.png") no-repeat top center;
          background-size: cover;

          .text {
            background-image: linear-gradient(115deg,
                #40b0f1b3 0%,
                #07e7f3b3 100%);
          }
        }

        &:nth-child(2) {
          background: url("~@/assets/image/pm.png") no-repeat top center;
          background-size: cover;

          .text {
            background-image: linear-gradient(115deg,
                #ff9102b3 0%,
                #ffa701b3 50%,
                #ffbb00b3 100%);
          }
        }

        &:nth-child(3) {
          background: url("~@/assets/image/vocs.png") no-repeat top center;
          background-size: cover;

          .text {
            background-image: linear-gradient(115deg,
                #0439cab3 0%,
                #07ecf4b3 100%);
          }
        }

        &:nth-child(4) {
          background: url("~@/assets/image/so2.png") no-repeat top center;
          background-size: cover;

          .text {
            background-image: linear-gradient(115deg,
                #6018d7b3 0%,
                #9d1fdfb3 100%);
          }
        }

        .top-triangle {
          display: block;
          width: 0px;
          height: 0px;
          border-style: solid;
          border-color: transparent;
          border-width: 6px;
          border-bottom-width: 6px;
          border-bottom-color: #fc6b58;
          position: absolute;
          top: 9px;
          right: 12px;
        }

        .btm-triangle {
          display: block;
          width: 0px;
          height: 0px;
          opacity: 0.3;
          border-style: solid;
          border-color: transparent;
          border-width: 6px;
          border-top-width: 6px;
          border-top-color: #0ce8ac;
          position: absolute;
          top: 9px;
          right: 12px;
          margin-top: 6px;
        }

        .num {
          box-sizing: border-box;
          margin-bottom: 17px;
          width: 100%;
          text-align: center;
          color: #f0f6fb;
          font-size: 22px;
          line-height: 1;
          white-space: nowrap;
          overflow: hidden;

          span {
            margin-left: 4px;
            font-size: 12px;
          }
        }

        .text {
          box-sizing: border-box;
          margin-bottom: 7px;
          width: 100px;
          height: 29px;
          text-align: center;
          color: #f0f6fb;
          font-size: 14px;
          line-height: 29px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          border-radius: 2px;
        }
      }
    }
  }

  .two {
    width: 100%;
    height: 219px;

    div {
      width: 100%;
      height: 100%;
    }
  }

  .three {
    width: 100%;
    padding-top: 37px;
    box-sizing: border-box;

    .title {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 22px;
      line-height: 1;
      color: #f0f6fb;
      box-sizing: border-box;
      margin-bottom: 30px;
    }

    .pro-list {
      width: 100%;

      .pro-item {
        width: 100%;
        display: flex;
        align-items: center;
        margin-bottom: 25px;

        &:last-child {
          margin-bottom: 0px;
        }

        &:nth-child(1) {
          .pro-label {
            .ranking {
              background: url("~@/assets/image/ranking-icon.svg") no-repeat center;
            }

            span {
              opacity: 1;
            }
          }

          .pro {
            ::v-deep .el-progress-bar__inner {
              background: linear-gradient(90deg, #1af5c4 0%, #05d3ff 100%);
            }
          }

          .num {
            span {
              opacity: 1;

              &:nth-child(1) {
                color: #08f5dc;
              }
            }
          }
        }

        &:nth-child(2) {
          .pro-label {
            .ranking {
              background: url("~@/assets/image/ranking-icon.svg") no-repeat center;
            }

            span {
              opacity: 1;
            }
          }

          .pro {
            ::v-deep .el-progress-bar__inner {
              background: linear-gradient(90deg, #0439ca 0%, #07ecf4 100%);
            }
          }

          .num {
            span {
              opacity: 1;

              &:nth-child(1) {
                color: #17a5f7;
              }
            }
          }
        }

        &:nth-child(3) {
          .pro-label {
            .ranking {
              background: url("~@/assets/image/ranking-icon.svg") no-repeat center;
            }

            span {
              opacity: 1;
            }
          }

          .pro {
            ::v-deep .el-progress-bar__inner {
              background: linear-gradient(90deg, #ff6e02 0%, #ffcc00 100%);
            }
          }

          .num {
            span {
              opacity: 1;

              &:nth-child(1) {
                color: #ffc100;
              }
            }
          }
        }

        .pro-label {
          display: flex;
          align-items: center;
          width: 118px;

          .ranking {
            width: 26px;
            height: 26px;
            background-size: contain;
            font-size: 14px;
            color: #e5edf7;
            line-height: 29px;
            text-align: center;
            margin-right: 11px;
          }

          span {
            font-size: 18px;
            line-height: 1;
            color: #e5edf7;
            opacity: 0.4;
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        .pro {
          width: calc(100% - 230px);

          ::v-deep .el-progress-bar {
            width: 315px;
            padding: 0px;
            margin: 0px;
          }

          ::v-deep .el-progress-bar__outer {
            border-radius: 0px;
            background: url("~@/assets/image/pro-bg.png") repeat-x center;
            background-size: contain;
          }

          ::v-deep .el-progress-bar__inner {
            border: 1px solid #060f2b;
            box-sizing: border-box;
            border-radius: 0px;
            background: linear-gradient(90deg, #2d3e73 0%, #102c86 100%);
          }

          ::v-deep .el-progress-bar__inner::after {
            position: absolute;
            top: -2px;
            right: -1px;
            width: 5px;
            height: 18px;
            background: url("~@/assets/image/pro-after.png") no-repeat center;
            background-size: cover;
          }

          ::v-deep .el-progress__text {
            width: calc(100% - 315px);
            margin-left: 0px;
            text-align: right;
          }
        }

        .num {
          width: 112px;
          display: flex;
          align-items: center;
          justify-content: flex-end;

          span {
            font-size: 18px;
            opacity: 0.4;

            &:nth-child(1) {
              flex: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              text-align: right;
              color: #e5edf7;
            }

            &:nth-child(2) {
              font-size: 16px;
              line-height: 1;
              color: #e5edf7;
              margin-left: 7px;
            }
          }
        }
      }
    }
  }
}
.title-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  margin: 0; // Remove default margins
  font-size: 22px;
  line-height: 1;
  color: #f0f6fb;
  white-space: nowrap;
}

.pollutant-selector {
  width: auto; // Remove fixed width
  min-width: 300px; // Allow shrinking
  margin-left: -450px; // Reduce spacing
}

.compact-radio-group {
  display: flex;
  flex-wrap: nowrap;
  gap: 10px; // Reduce spacing between items
}

.compact-radio {
  margin-right: 0 !important; // Remove default margin

  ::v-deep .el-radio__label {
    font-size: 11px; // Smaller text
    padding-left: 4px; // Reduce label padding
  }

  ::v-deep .el-radio__inner {
    width: 12px;
    height: 12px; // Smaller radio circles
  }
}
</style>
